package com.rongji.cms.tools.common.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

/**
 * @author yang
 * @date 2022/12/1 13:12
 * @description
 */

@Aspect
@Component
@Slf4j
public class CostTimeAspect {
    //定义一个切点。指向我们的注解类
    @Pointcut(value = "@annotation(com.rongji.cms.tools.common.annotation.CostTime)")
    public void CostTime() {
    }

    // 使用@Around环绕通知， 环绕通知=前置通知+目标方法执行+后置通知
    @Around("CostTime()")
    public Object doAround(ProceedingJoinPoint joinPoint) { //ProceedingJoinPoint可以获取当前方法和参数等信息
        Object obj = null;
        try {
            StopWatch stopWatch = new StopWatch();
            stopWatch.start();
            obj = joinPoint.proceed();
            //获取方法名称
            String methodName = joinPoint.getSignature().getName();
            //获取类名称
            String className = joinPoint.getSignature().getDeclaringTypeName();
            stopWatch.stop();
            log.info("类:[{}]，方法:[{}]耗时时间为:[{}]", className, methodName, stopWatch.getTotalTimeSeconds() + "秒");
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return obj;
    }


//    @Around("execution(* com.rongji..*ServiceImpl.*(..))")
//    public Object logServiceMethodAccess(ProceedingJoinPoint joinPoint) { //ProceedingJoinPoint可以获取当前方法和参数等信息
//        Object obj = null;
//        try {
//            StopWatch stopWatch = new StopWatch();
//            stopWatch.start();
//            obj = joinPoint.proceed();
//            //获取方法名称
//            String methodName = joinPoint.getSignature().getName();
//            //获取类名称
//            String className = joinPoint.getSignature().getDeclaringTypeName();
//            stopWatch.stop();
//            log.info("类:[{}]，方法:[{}]耗时时间为:[{}]", className, methodName, stopWatch.getTotalTimeSeconds() + "秒");
//        } catch (Throwable throwable) {
//            throwable.printStackTrace();
//        }
//        return obj;
//    }
}

